package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private EmpService empService;

    /**
     * 条件分页查询班级
     * @param name
     * @param begin
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult pageQuery(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> pageClazz = Page.of(page, pageSize);
        pageClazz.addOrder(OrderItem.desc("update_time"));
        Page<Clazz> pageResult = lambdaQuery()
                .like(StrUtil.isNotBlank(name), Clazz::getName, name)
                .between(ObjectUtil.isNotEmpty(begin) || ObjectUtil.isNotEmpty(end), Clazz::getBeginDate, begin, end)
                .page(pageClazz);
        //处理班主任名称
        List<Clazz> clazzList = pageResult.getRecords();
        Set<Integer> MasterIds = clazzList.stream().map(Clazz::getMasterId).collect(Collectors.toSet());
        List<Emp> empList = empService.listByIds(MasterIds);
        Map<Integer, String> empMap = empList.stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
        clazzList.forEach(clazz -> {
            clazz.setMasterName(empMap.getOrDefault(clazz.getMasterId(), "暂未分配班主任"));
            clazz.setStatus(clazz.getEndDate().isAfter(LocalDate.now()) ?
                    (clazz.getBeginDate().isBefore(LocalDate.now()) ? "在读" : "未开班") : "已结课");
        });
        return new PageResult(pageResult.getTotal(), clazzList);
    }
}
